import { defineStore } from 'pinia'
import { getUser, userLogin } from '@/utils/api/user/userApi'
import type { profile, loginUser, getProfile } from '@/utils/api/user/userType'
import { ref } from 'vue'
import { useToastStore } from '@/stores/modules/toast'
// 用户相关
export const useUserStore = defineStore(
  'user',
  () => {
    const profile = ref<profile | undefined>(undefined) // 登陆后获取的信息
    const userfile = ref<getProfile | undefined>(undefined) // 保存用户信息
    const toastStore = useToastStore()
    const getLogin = async (e: loginUser, url?: string) => {
      uni.showLoading({ title: '登录中' })
      const resLogin = await userLogin(e)
      profile.value = resLogin.data // 保存登录信息
      const resUser = await getUser({ userId: profile.value?.userId as string })
      uni.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500,
      })
      toastStore.show = true
      toastStore.type = true
      toastStore.title = '登录成功'
      userfile.value = resUser.data // 保存用户信息
      setTimeout(() => {
        uni.redirectTo({
          url: url ? url : '/pages/index/index',
        })
      }, 1500)
    }

    const exitLogin = () => {
      profile.value = undefined
      userfile.value = undefined
    } // 退出登录，清除信息
    // 记得 return
    return { profile, userfile, getLogin, exitLogin }
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
      paths: ['profile', 'userfile'],
    },
  },
)
